import numpy as np
import matplotlib.pyplot as plt
import cv2
mask = 0
zeros = 0
def auto_read_zone(img_pwd,pos_r,rad_r):
    global mask
    global zeros
    img = cv2.imread(img_pwd,1)
    #img = cv2.imread('./img/1106/1106cam/7 (2).PNG',1)
    print('img info:')
    print('shape:',img.shape,' pixal num:',img.size,' dtype:',img.dtype)
    zeros = np.zeros(img.shape[:2], dtype = "uint8")
    mask= np.zeros(img.shape[:2], dtype = "uint8")

    #RGB拆分
    b,g,r=cv2.split(img)
    #RGB组合br
    #img2=cv2.merge([b,g,r])

    def show_num(y,x):
        global mask
        #半径
        rad=rad_r
        cv2.circle(mask,(y,x),rad,(255,0,0),-1)
        res=cv2.bitwise_and(pro_img_tmp,pro_img_tmp,mask=mask)
        #cv2.imshow('res',res)
        plt.hist(res.ravel(),256,[1,256]);#灰度直方图
        #plt.show()
        #print('shape:',res.shape,' pixal num:',res.size,' dtype:',res.dtype)
        #s=np.pi*((rad)**2)
        ave=np.sum(res)/np.sum(res>0)
        print(np.sum(res),"    ",ave)
        
        #print(np.sum(res),"    ",np.sum(res)/s)
        #print(np.sum(res>0),'   ',s)
        res=np.zeros(img.shape[:2], dtype = "uint8")
        mask=np.zeros(img.shape[:2], dtype = "uint8")

        #print('POS:(',x,y,') R:',r,'G:',g,'B:',b)
        #print('POS:(',x,y,')' ,img.item(x,y,0),img.item(x,y,1),img.item(x,y,2))
        print('POS:(',x,y,')' ,r[x][y])
        #ave=get_gray_value(r,[x,y],d)
        
        print('average :(',x,y,')' ,ave)
        cv2.circle(pro_img,(y,x),rad,(0,255,0),1)
        cv2.circle(pro_img,(y,x),1,(0,255,0),-1)
        cv2.putText(pro_img,str(round(ave,3)),(y+15,x-15), cv2.FONT_HERSHEY_SIMPLEX, 1,(0,65,255),1)
        
        #plt.show()

    pro_img=cv2.merge([r, r, r])
    pro_img_tmp=r
    show_num(pos_r[0],pos_r[1])
    cv2.namedWindow('image')
    cv2.imshow('image',pro_img)
    while(1):
        key=cv2.waitKey(1)&0xFF
        if key==27:
            break
        if cv2.getWindowProperty('image', cv2.WND_PROP_AUTOSIZE) < 1:
            break
    cv2.destroyAllWindows()       